import { Component, OnInit } from '@angular/core';
import { MessageService } from 'src/app/core/service/message.service';
import { ApiService } from 'src/app/core/api';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { StorageService } from 'src/app/core/sotrage/storage.service';
import { UtilService } from 'src/app/core/util/util';

@Component({
    templateUrl: './index.html',
    styleUrls: ['./index.scss']
})
export class SMRZComponent implements OnInit {
    form: FormGroup;
    formType = 'over';
    current = 0;
    // formType = 'over';
    idcardFrontPhoto;
    idcardBackPhoto;
    idCardHoldPhoto;
    pageDel
  
    ngOnInit() {
      this.pageDel = this.sto.get('user');
      if(this.pageDel){
        this.form = this.fb.group({
          name: [null,
            [Validators.required]
          ],
          idCardNum: [null, [Validators.required,this.cardIdValidator]],
        });
      }else{
        // this.router.navigate(['pages/login']);
      }
    }
    public cardIdValidator = (control: FormControl): { [s: string]: boolean } => {
      if (control.value && !this.util.IdentityCodeValid(control.value)) {
          return { card: true, error: true };
      }
      return {};
    }
    next() {
      this.current = 1;
      this.formType = 'updateImg';
    }
  
    submit() {
      let data;
      console.log(this.idcardFrontPhoto)
      console.log(this.idcardBackPhoto)
      console.log(this.idCardHoldPhoto)
      if (!this.idcardFrontPhoto || !this.idcardBackPhoto || !this.idCardHoldPhoto) {
        this.msg.warning('身份证上传不正确，请重新上传。');
      } else {
        data = Object.assign({ idcardFrontPhoto: this.idcardFrontPhoto, idcardBackPhoto: this.idcardBackPhoto ,idCardHoldPhoto:this.idCardHoldPhoto}, this.form['value']);
        this.api.post('实名认证', data).then((res: any) => {
          this.getUser({mobile:this.sto.get('user')['mobile']});
        }).catch((res) => {
          this.msg.error(res.data.message);
        });
      }
    }
  
    getUser(data){
      this.api.post('用户详情', data).then(res => {
        let userMap = res['data']['whiteHatUserDetail'];
        if(userMap['idcardAuthStatus'] == 'APPROVED'){
          userMap = Object.assign(userMap,{isSMRZ:true});
          this.msg.success('实名成功')
        }else if(userMap['idcardAuthStatus'] == 'PENDING'){
          this.formType = 'over';
        }else{
          userMap = Object.assign(userMap,{isSMRZ:false});
        };
        localStorage.setItem('user', JSON.stringify(userMap));
      }).catch(res => {
        this.msg.error(res.data.message);
      });
    }
    
    back(type){
      this.formType = type;
  
    }

    constructor(
        private fb: FormBuilder,
        private util:UtilService,
        private message: MessageService,
        private msg: NzMessageService,
        private sto: StorageService,
        private api: ApiService
    ) { }
}